<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.category" clearable style="width: 200px;" placeholder="请输入分类名称" />
      <el-button type="primary" icon="el-icon-search" @click="getList">查找</el-button>
      <el-button type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button
        :disabled="multipleSelection.length===0"
        type="danger"
        icon="el-icon-delete"
        @click="handleDeleteAll"
      >批量删除</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      row-key="categoryId"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="类目ID" prop="categoryId" />

      <el-table-column align="center" label="分类名称" prop="category" />

      <el-table-column align="center" label="商品数量" prop="goodsCount">
        <template slot-scope="scope">
          <div>{{ scope.row.goodsCount }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="已上架商品数量" prop="goodsCountPublished">
        <template slot-scope="scope">
          <div>{{ scope.row.goodsCountPublished }}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="分类状态">
        <template slot-scope="scope">
          <el-badge
            :type="scope.row.showStatus===1?'success':'danger'"
            is-dot
            class="item"
          >{{ scope.row.showStatus===1 ? '显示' : '隐藏' }}</el-badge>
        </template>
      </el-table-column>
      <el-table-column align="center" label="排序" prop="sortNo" />
      <el-table-column align="center" label="创建时间" width="200" prop="created" />

      <el-table-column align="center" label="操作" width="260" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="getDetail(scope.row,true)">详情</el-button>
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button type="danger" size="mini" @click="handleDelete(scope.row.categoryId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="分类名称" prop="category">
          <el-input v-model="dataForm.category" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="分类状态" prop="showStatus">
          <el-radio-group v-model="dataForm.showStatus" :disabled="disabled">
            <el-radio :label="1">显示</el-radio>
            <el-radio :label="0">隐藏</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item v-if="dataForm.categoryId" label="商品数量" prop="goodsCount">
          <el-input v-model="dataForm.goodsCount" :disabled="disabled" />
        </el-form-item>-->
        <!-- <el-form-item v-if="dataForm.categoryId" label="已上架商品数量" prop="goodsCountPublished">
          <el-input v-model="dataForm.goodsCountPublished" :disabled="disabled" />
        </el-form-item>-->
        <el-form-item label="排序" prop="sortNo">
          <el-input v-model="dataForm.sortNo" :disabled="disabled" />
        </el-form-item>
      </el-form>
      <div v-if="!disabled" slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.filter-item {
  margin-left: 100px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}

.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {
  listCategory,
  createCategory,
  updateCategory,
  deleteCategory
} from '@/api/category'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import lodash from 'lodash'
export default {
  name: 'Category',
  components: {
    Pagination
  },
  data() {
    return {
      uploadPath,
      list: [],
      listLoading: true,
      dataForm: {
        categoryId: '',
        category: '',
        showStatus: 1,
        sortNo: '',
        goodsCount: '',
        goodsCountPublished: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
        detail: '详情'
      },
      rules: {
        category: [
          {
            required: true,
            message: '分类名称不能为空',
            trigger: 'blur'
          }
        ],
        showStatus: [
          {
            required: true,
            message: '请选择分类状态',
            trigger: 'change'
          }
        ],
        sortNo: [
          {
            required: true,
            message: '分类排序不能为空',
            trigger: 'blur'
          }
        ]
      },
      total: 0,
      listQuery: {
        category: null,
        index: 0,
        size: 10
      },
      multipleSelection: [],
      disabled: false
    }
  },
  computed: {
    headers() {
      return {
        'X-Litemall-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取列表
    getList(e) {
      if (e && e.page) {
        this.listQuery.index = e.page - 1
      }
      this.listLoading = true
      listCategory(this.listQuery)
        .then(response => {
          this.list = response.data.data.content
          this.total = response.data.data.totalRecords
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.listLoading = false
        })
    },
    resetForm() {
      this.disabled = false
      this.dataForm = {
        categoryId: '',
        category: '',
        showStatus: 1,
        sortNo: '',
        goodsCount: '',
        goodsCountPublished: ''
      }
    },
    // 添加
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    // 新建类目
    createData: lodash.debounce(function() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          createCategory(this.dataForm)
            .then(response => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '后台接口出错了'
              })
            })
        }
      })
    }, 3000),
    // 编辑
    handleUpdate(row) {
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.disabled = false
      this.dataForm.categoryId = row.categoryId
      this.dataForm.category = row.category
      this.dataForm.showStatus = row.showStatus
      this.dataForm.sortNo = row.sortNo
      this.dataForm.goodsCount = row.goodsCount
      this.dataForm.goodsCountPublished = row.goodsCountPublished
    },
    // 更新类目
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          updateCategory(this.dataForm)
            .then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleDelete: lodash.throttle(function(id) {
      this.$confirm('此操作将永久删除该类目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const params = {
            idList: [id]
          }
          deleteCategory(params).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    }, 3000),
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },
    handleDeleteAll: lodash.throttle(function() {
      const idList = []
      this.multipleSelection.forEach(item => {
        idList.push(item.categoryId)
      })
      deleteCategory({
        idList
      }).then(res => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getList()
      })
    }, 3000),
    // 获取分类详情
    getDetail(row, disabled) {
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.disabled = true
      this.dataForm.categoryId = row.categoryId
      this.dataForm.category = row.category
      this.dataForm.showStatus = row.showStatus
      this.dataForm.sortNo = row.sortNo
      this.dataForm.goodsCount = row.goodsCount
      this.dataForm.goodsCountPublished = row.goodsCountPublished
    }
  }
}
</script>
<style lang="scss" >
</style>
